package com.njzxw.fs.serversys.server;

import com.njzxw.fs.commonutil.util.StringHelper;
import com.njzxw.fs.commonutil.web.BaseServer;
import com.njzxw.fs.commonutil.web.ReturnMap;
import com.njzxw.fs.serversys.bean.Node;
import com.njzxw.fs.serversys.bean.OrgBean;
import com.njzxw.fs.serversys.bean.State;
import com.njzxw.fs.serversys.repository.OrgReq;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrgServer extends BaseServer{

    @Autowired
    private OrgReq orgReq;

    /**
     * 获取组织信息
     *
     * @param request
     * @param response
     * @return
     */
    public ReturnMap getOrgList(HttpServletRequest request,
                                HttpServletResponse response,OrgBean orgBean) {
        if(orgBean.getType() == 1){
            returnMap.setDataMaps(orgReq.getOrgList(orgBean));
        }else{
            returnMap.setDataMaps(getOrg(orgReq.getOrgList(orgBean),orgReq.getOrgUserCnt(),"0"));
        }
        return returnMap.getSucceeReturnMaps();
    }

    /**
     * 获取菜单
     * @param list
     * @param userlist
     * @param supperid
     * @return
     */
    private List<Node> getOrg(List<Map<String,Object>> list,List<Map<String,Object>> userlist, String supperid){
        List<Node> listNode = new ArrayList<>();

        for(int i=0;i< list.size();i++){

            String id = StringHelper.get(list.get(i),"id");
            String supper_id = StringHelper.get(list.get(i),"supper_id");
            if(supperid.equals(supper_id)){
                Node node = new Node();
                node.setId(id);
                node.setSupper_id(supperid);
                node.setText(StringHelper.get(list.get(i),"org_name"));
                node.setSupper_id(StringHelper.get(list.get(i),"supper_id"));

                List<Node> nodes = getOrg(list,userlist,id);

                List<String> tags = new ArrayList();
                tags.add(getOrgUserCnt(userlist,id));
                node.setTags(tags);

                node.setState(new State());
                if(nodes.size() > 0){
                    node.setNodes(nodes);
                }

                listNode.add(node);
            }

        }

        return listNode;
    }

    private String getOrgUserCnt(List<Map<String,Object>> userlist,String org_id){
        for(int i=0,cnt = userlist.size();i<cnt;i++){
            userlist.get(i).get(org_id);
            String cnts = StringHelper.get(userlist.get(i),org_id);
            if(!"".equals(cnts)){
                return cnts;
            }
        }
        return "0";
    }

    /**
     * 保存组织信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ReturnMap saveOrgInfo(HttpServletRequest request,
                                 HttpServletResponse response,OrgBean orgBean) {
        logger.debug("orgBean:"+orgBean.getId()+"==="+orgBean.getSupper_id_list().split(",").length);
        if(StringUtils.isBlank(orgBean.getSupper_id_list())){
            orgBean.setLevel(1);
        }else {
            orgBean.setLevel(orgBean.getSupper_id_list().split(",").length + 1);
        }
        if(org.apache.commons.lang3.StringUtils.isBlank(orgBean.getSupper_id())){
            orgBean.setSupper_id("0");
        }

        if(StringUtils.isBlank(orgBean.getId())){
            if(orgReq.insert(orgBean) != 1){
                return returnMap.getErrorReturnMap("操作失败");
            }
        }else{
            if(orgBean.getId().equals(orgBean.getSupper_id())){
                return returnMap.getErrorReturnMap("上级组织不能选择自己哦");
            }
            if(orgReq.update(orgBean) != 1){
                return returnMap.getErrorReturnMap("操作失败");
            }
        }
        //给他所有上级ID组织添加此下级集合
        //查询出所有上级
        List<Map<String,Object>> superList = orgReq.getSuperList(orgBean.getId());
        logger.debug("superList:"+superList);

        if(superList != null && !superList.isEmpty() && superList.size() != 1){
            List<String> supperListIds = new ArrayList<>();
            for(int i=0;i<superList.size();i++){
                String id_ = StringHelper.get(superList.get(i),"id");
                if(!id_.equals(orgBean.getId())){
                    supperListIds.add(id_);
                }
            }
            orgBean.setSupperListIds(supperListIds);

            logger.debug("orgBean:"+orgBean.toString());

            Integer exc = orgReq.updateSupper(orgBean);

            if(exc == null || exc < 0){
                return returnMap.getErrorReturnMap("操作失败");
            }

        }

        return returnMap.getSucceeReturnMaps("保存成功");
    }

    /**
     * 删除组织信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public ReturnMap deleteOrg(HttpServletRequest request,
                               HttpServletResponse response,OrgBean orgBean) {
        OrgBean orgBean1 = new OrgBean();
        orgBean1.setSupper_id(orgBean.getId());
        if(!orgReq.getOrgList(orgBean1).isEmpty()){
            return returnMap.getErrorReturnMap("该组织存在下级组织，不予删除，请先删除下级组织！");
        }
        if(orgReq.delete(orgBean) != 1){
            return returnMap.getErrorReturnMap("删除失败，请重新操作");
        }
        return returnMap.getSucceeReturnMaps("操作成功");
    }

    /**
     * 获取单条组织信息
     *
     * @param request
     * @param response
     * @return
     */
    public ReturnMap getOrgMap(HttpServletRequest request,
                            HttpServletResponse response) {

        return returnMap.getSucceeReturnMaps();
    }

    public ReturnMap getOrgMap(HttpServletRequest request, HttpServletResponse response, OrgBean orgBean) {
        Map<String,Object> map = orgReq.getOrgMap(orgBean);

        //获取出对应上级所有信息
        String supper_id = StringHelper.get(map,"supper_id");
        String id = StringHelper.get(map,"id");

        setSupperMap(supper_id,map);

        returnMap.setDataMaps(map);
        return returnMap.getSucceeReturnMaps();
    }

    public void setSupperMap(String supper_id,Map<String,Object> map){
        OrgBean orgBean = new OrgBean();
        orgBean.setId(supper_id);
        Map<String,Object> map_ = orgReq.getOrgMap(orgBean);
        if(map_ == null){
            return;
        }
        int level = Integer.valueOf(StringHelper.get(map_,"level"))-1;
//        System.out.println("????????=:"+level);
        String supperid = StringHelper.get(map_,"supper_id");
        String id = StringHelper.get(map,"id");

        map.put("supper_id"+level,supper_id);

        setSupperMap(supperid,map);
    }

}
